package com.ruoyi.common.config;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 * @RestControllerAdvice 统一处理所有RestController的异常
 */
@RestControllerAdvice
public class GlobalExceptionResolve {
//    方法参数校验异常处理 MethodArgumentNotValidException
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.OK)
    public void notValid(MethodArgumentNotValidException e, HttpServletResponse response) throws IOException {
    String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
    response.setCharacterEncoding("UTF-8");
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.getWriter().write(JSON.toJSONString(AjaxResult.error(defaultMessage)));
}
}
